<?php

namespace App\Http\Controllers\Api;

use App\Model\GroupList;
use App\Model\ConfigModel;
use App\Model\GroupListLog;
use App\Model\GroupListOrder;
use App\Model\GroupListCite;
use App\Model\UserModel;
use App\Model\CityModel;
use App\Model\UserWalletModel;
use App\Model\UserLoginModel;
use App\Model\UserAddressModel;
Use App\Model\ShopGoodModel;
use App\Services\Group;
use Illuminate\Http\Request;
use App\Model\ShopGoodPicModel;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

//拼团
class GroupController extends Controller
{
    //列表
    public function index(Request $request){
        $uid = request()->header('uid');
        if($uid != 1271){
            $val = ConfigModel::getValue('switch_state');
            if($val == 2){
                return ['code'=>0,'msg'=>"拼团当前暂不开放"];
            }
        }
        
        $type = $request->input('type',1);
        //时间
        $time = date('Y-m-d 00:00:00');
        $tomorrow = date('Y-m-d 00:00:00',strtotime('+1 day'));
        //现在的时间
        $now = time();

        //拼团列表
        if($type == 1){
            $list = GroupList::where('start','<',$time)->orderby('switch','asc')->orderBy('end','asc')->paginate(10);
        }elseif($type == 2){
            $list = GroupList::where('start','>=',$time)->where('start','<',$tomorrow)->orderby('switch','asc')->orderBy('end','asc')->paginate(10);
        }else{
            $list = GroupList::where('start','>=',$tomorrow)->orderby('switch','asc')->orderBy('end','asc')->paginate(10);
        }
        
        //处理数据
        $arr = [];
        foreach($list as $k=>$v){
            $arr[$k]['id'] = $v['id'];
            $arr[$k]['picname'] = $v['picname'];
            $arr[$k]['name'] = $v['name'];
            $arr[$k]['charge'] = ceil($v['charge']/$v['nums']);
            $arr[$k]['shares'] = $v['shares'];
            $arr[$k]['sell'] = $v['sell'];
            $arr[$k]['time'] = strtotime($v['end']);
            //中奖的用户
            $arr[$k]['win_user_pic'] = "http://".$_SERVER['HTTP_HOST'].'/user.png';
            //中奖的用户联系方式
            $arr[$k]['win_user_tel'] = '130****0897';
            //中奖的订单信息
            $win_order = GroupListLog::where('gid',$v['id'])->where('curcle',$v['curcle'])->where('state',3)->first();
            if($win_order){
                //用户信息
                $user = UserModel::where('id',$win_order['uid'])->first();
                if($user['email']){
                    $arr[$k]['win_user_tel'] = substr_replace($user['email'], '****', 3, 4);
                }
                if($user['phone']){
                    $arr[$k]['win_user_tel'] = substr_replace($user['phone'], '****', 3, 4);
                }
                
                //第三方
                $party = UserLoginModel::where('uid',$user['id'])->first();
                if(!$user['picname']){
                    if($party['picname']){
                        $arr[$k]['win_user_pic'] = $party['picname'];
                    }
                }else{
                    $arr[$k]['win_user_pic'] = 'http://'.$_SERVER['HTTP_HOST'].$user['picname'];
                }
            }
            //已经买了多少个
            $arr[$k]['in_nums'] = GroupListLog::where('gid',$v['id'])->where('curcle',$v['curcle'])->count();
            $arr[$k]['nums'] = $v['nums'];
            $arr[$k]['state'] = $v['switch'];
            if($type == 3){
                $arr[$k]['state'] = 3;
            }else{
                if(strtotime($v['start']) > $now){
                    $arr[$k]['state'] = 3;
                }
            } 
            
        }
        return ['code'=>1,'msg'=>'返回数据','data'=>$arr];
    }

    //商品详情
    public function detail(){
        $uid = request()->header('uid');
        if($uid != 1271){
            $val = ConfigModel::getValue('switch_state');
            if($val == 2){
                return ['code'=>0,'msg'=>"拼团当前暂不开放"];
            }
        }
        $id = request()->id;
        $list = GroupList::where('id',$id)->first();
        if(!$list){
            return ['code'=>0,'msg'=>'商品信息有误'];
        }
        DB::beginTransaction();
        try{
            $res['id'] = $list['id'];
            $res['name'] = $list['name'];
            $res['picname'] = $list['picname'];

            $piclist[] = $list['picname'];
            $pics = ShopGoodPicModel::where('gid',$list['gid'])->select('picname','oss_pic')->limit(5)->get();
		    if(count($pics) > 0){
                foreach($pics as $v){
                    if($v['oss_pic']){
                        $piclist[] = $v['oss_pic'];
                    }else{
                        $piclist[] = "http://".$_SERVER['HTTP_HOST'].$v['picname'];
                    }
                }
            }
            $state = 1;
            if($list['start'] > date('Y-m-d H:i:s')){
                $state = 2;
            }
            //商品信息
            $good = ShopGoodModel::where('id',$list['gid'])->first();
            $res['content'] = $good['content'];
            $res['content'] = str_replace('/upload','http://'.$_SERVER['HTTP_HOST'].'/upload',$res['content']);
            $res['content'] = str_replace("table width=\"790\"","table width=\"100%\"",$res['content']);
            $res['content'] = str_replace("<img ","<img style='width:100%' ",$res['content']);
            $res['sell'] = $list['sell'];
            $res['end'] = strtotime($list['end']);
            $res['start'] = strtotime($list['start']);
            $res['state'] = $state;
            $add_order = GroupListLog::where('gid',$res['id'])->where('curcle',$list['curcle'])->get();
            //用户头像
            $pic = [];
            foreach($add_order as $k=>$v){
                //用户信息
                $user = UserModel::where('id',$v['uid'])->first();
                //用户的头像
                $user_party = UserLoginModel::where('uid',$v['uid'])->first();
                if($user['picname']){
                    $pic[] = "http://".$_SERVER['HTTP_HOST'].$user['picname'];
                }else{
                    if($user_party['picname']){
                        $pic[] = $user_party['picname'];
                    }else{
                        $pic[] = 'http://'.$_SERVER['HTTP_HOST'].'/img/user.png';
                    }
                }
               
            }
            
            DB::commit();
        }catch(Exception $e){
            DB::rollBack();
        }
        $data['res'] = $res;
        $data['pic'] = $pic;
        $data['piclist'] = $piclist;
        return ['code'=>1,'msg'=>"返回数据",'data'=>$data];
    }

    //立即抢购，选择拼团位置,加载数据
    public function is_buy_sure(){
        $uid = request()->header('uid');
        if($uid != 1271){
            $val = ConfigModel::getValue('switch_state');
            if($val == 2){
                return ['code'=>0,'msg'=>"拼团当前暂不开放"];
            }
        }
        //拼团商品ID
        $id = request()->id;
        //商品信息
        $list = GroupList::where('id',$id)->where('switch',1)->first();
        if(!$list){
            return ['code'=>0,'msg'=>"该商品不存在或者停止拼团"];
        }
        //地址信息
        $is_address = 1;
        $arr['id'] = 0;
        $arr['name'] = '';
        $arr['phone'] = '';
        $arr['address'] = '';
        //获取用户的地址
        $address = UserAddressModel::where('uid',request()->uid)->where('is_default',1)->first();
        if(!$address){
            $address = UserAddressModel::where('uid',request()->uid)->whereNull('cid')->orderBy('id','desc')->first();
            if(!$address){
                $is_address = 2;
            }
        }
        if($address){
            $arr['id'] = $address['id'];
            $arr['name'] = $address['name'];
            $arr['phone'] = $address['phone'];
            $arr['address'] = CityModel::city($address['provinceid']).CityModel::city($address['cityid']).CityModel::city($address['countyid']).$address['detail'];
        }
     
        $aid = request()->aid;
        $address = UserAddressModel::where('id',$aid)->first();
        if($address){
            $arr['id'] = $address['id'];
            $arr['name'] = $address['name'];
            $arr['phone'] = $address['phone'];
            $arr['address'] = CityModel::city($address['provinceid']).CityModel::city($address['cityid']).CityModel::city($address['countyid']).$address['detail'];
        }


        //拼团信息
        $nums = [];
        //该商品有几个拼团数
        $times = $list['nums'];
        for($i=0;$i<$times;$i++){
            $nums_cy = $i+1;
            $nums[$i]['nums'] = $nums_cy.'号';
            $nums[$i]['is_exit'] = 1;
            $is_exit = GroupListLog::where('gid',$list['id'])->where('curcle',$list['curcle'])->where('num',$i+1)->first();
            if($is_exit){
                $nums[$i]['is_exit'] = 2;
            }
        }
        $data['address'] = $arr;
        $data['nums'] = $nums;
        $data['is_add'] = $is_address;
        return ['code'=>1,'msg'=>"返回数据",'data'=>$data];
        
    }

    //下单
    public function is_buy(Request $request){
        $uid = request()->header('uid');
        if($uid != 1271){
            $val = ConfigModel::getValue('switch_state');
            if($val == 2){
                return ['code'=>0,'msg'=>"拼团当前暂不开放"];
            }
        }
        //选择的位置
        $sites = $request->input('sites');
        //用户ID
        $uid = $request->input('uid');
        //拼团商品ID
        $gid = $request->input('gid');
        //地址信息
        $linkman = $request->input('linkman');
        $linktel = $request->input('linktel');
        $address = $request->input('address');
        //支付密码
        $paypass = $request->input('paypass');
        //拼团数
        $site_num = $request->input('site_num');
        //判断支付方式 1现金 2货款 3微信  4支付宝
        $paytype = $request->input('paytype',1);

        //计算选择的位置和拼团数是否一致
        $sites = explode(',',trim($sites,','));
        if(count($sites) != $site_num){
            return ['code'=>0,'msg'=>'请确认选择的拼团数'];
        }
        //用户的信息
        $user = UserModel::where('id',$uid)->first();
        if(!$user){
            return ['code'=>0,'msg'=>'用户信息有误'];
        }
        if($user['is_auth'] != 1){
            return ['code'=>'0','msg'=>'未实名不可以参与拼团'];
        }
        //拼团商品的信息
        $good = GroupList::where('id',$gid)->first();
        if(!$good){
            return ['code'=>0,'msg'=>'商品信息有误'];
        }
        $now_time = date('Y-m-d H:i:s');
        if($good['start'] > $now_time){
            return ['code'=>0,'msg'=>'当前商品暂未开启拼团活动'];
        }
        if($good['end'] < $now_time){
            return ['code'=>0,'msg'=>'当前商品拼团活动已过期'];
        }
        //地址
        if(!$linkman && !$linktel && !$detail){
            return ['code'=>0,'msg'=>'请选择地址'];
        }
        //支付密码
        if (!Hash::check($paypass, $user['paypass'])) {
            return ['code' => 0, 'msg' => '支付密码输入有误'];
        }
        //计算总价
        $sum = $good['sell'] * $site_num;
        
        //判断金额是否足够
        $user_wallet = UserWalletModel::where('uid',$uid)->first();
        //开启事务
        DB::beginTransaction();
        try{
            //查询这几个位置是否已经被买
            foreach($sites as $k=>$v){
                $is_buy_site_list = GroupListLog::where('num',$v)->where('gid',$gid)->where('curcle',$good['curcle'])->LockForUpdate()->first();
                if($is_buy_site_list){
                    return ['code'=>0,'msg'=>$v.'号已售，请重新选择'];
                }
                if($v > $good['nums']){
                    return ['code'=>0,'msg'=>'位置选择异常'];
                }
            }
            //支付方式，计算余额
            switch($paytype){
                case '1':
                    if($user_wallet['money'] < $sum){
                        return ['code'=>0,'msg'=>'现金余额不足'];
                    }
                    break;
                case '2':
                    if($user_wallet['lock_money'] < $sum){
                        return ['code'=>0,'msg'=>'货款余额不足'];
                    }
                    break;
            }


            $sn = GroupListOrder::make_no_g();
            //生成订单
            $order = GroupListOrder::create([
                'uid' => $uid,
                'gid' => $gid,
                'num' => $site_num,
                'gname' => $good['name'],
                'sell' => $good['sell'],
                'sum' => $good['sell'] * $site_num,
                'curcle' => $good['curcle'],
                'paytype' => $paytype,
                'sn' => $sn,
                'linkman' => $linkman,
                'linktel' => $linktel,
                'address' => $address,
            ]);
            foreach($sites as $k=>$v){
                //生成子订单
                GroupListLog::create([
                    'uid' => $uid,
                    'oid' => $order['id'],
                    'gid' => $gid,
                    'curcle' => $good['curcle'],
                    'sell' => $good['sell'],
                    'num' =>  $v,
                    'group_num' => $good['nums'],
                    'shares' => $good['shares'],
                    'charge' => ceil($good['charge']/$good['nums']),

                ]);
            }
            //扣钱
            //增加扣除日志
            
            if($paytype == 1 || $paytype == 2){
                UserWalletModel::handleAccount($uid,$good['sell'] * $site_num,'-','拼团下单',$paytype,16);
            }else{
                return ['code'=>0,'msg'=>'暂未开通'];
            }
			
            //判断是否拼团成功 
            Group::charge($gid,$good['curcle']);
            DB::commit();
        }catch(Exeption $e){
            DB::rollBack();
            return ['code'=>0,'msg'=>"拼团失败"];
        }
        return ['code'=>1,'msg'=>"拼单成功"];
    }
    

    //我的订单
    public function order(){
        $uid = request()->header('uid');
        if($uid != 1271 && $uid != 1244){
            $val = ConfigModel::getValue('switch_state');
            if($val == 2){
                return ['code'=>0,'msg'=>"拼团当前暂不开放"];
            }
        }
        $uid = request()->uid;
        $order = [];
        $list = GroupListOrder::where('uid',$uid)->orderBy('id','desc')->get();
        foreach($list as $k=>$v){
            $group = GroupListCite::where('gid',$v['gid'])->where('curcle',$v['curcle'])->first();
            if($group){
                $order[$k]['picname'] = $group['gpic'];
                $order[$k]['name'] = $group['gname'];
            }else{
                $group_two = GroupList::where('id',$v['gid'])->first();
                $order[$k]['picname'] = $group_two['picname'];
                $order[$k]['name'] = $group_two['name'];
            }
            
            $order[$k]['id'] = $v['id'];
            $order[$k]['sell'] = $v['sell'];
            $order[$k]['sum'] = $v['sum'];
            $order[$k]['num'] = $v['num'];
            $order[$k]['sn'] = $v['sn'];
            $order[$k]['send'] = 2;
           
            //购买记录
            $state = 1;//拼团(4拼团失败 3中奖  2未中奖  1待成团)
            if(GroupListLog::where('oid',$v['id'])->where('state',4)->first()){
                $state = 4;
            }
            if(GroupListLog::where('oid',$v['id'])->where('state',2)->first()){
                $state = 2;
            }
            if(GroupListLog::where('oid',$v['id'])->where('state',1)->first()){
                $state = 1;
            }
            if(GroupListLog::where('oid',$v['id'])->where('state',3)->first()){
                $state = 3;
                $list = GroupListLog::where('oid',$v['id'])->where('state',3)->first();
                if($list['status'] != 1){
                    $order[$k]['send'] = 1;
                }else{
                    $order[$k]['send_time'] = $list['send_time'];
                }
                $order[$k]['status'] = $list['status'];
            }
            $order[$k]['state'] = $state;
        }

        return ['code'=>1,'msg'=>'返回数据','data'=>$order];
    }

    //订单详情
    public function order_de(){
        $uid = request()->header('uid');
        if($uid != 1271){
            $val = ConfigModel::getValue('switch_state');
            if($val == 2){
                return ['code'=>0,'msg'=>"拼团当前暂不开放"];
            }
        }
        $oid = request()->oid;
        //订单信息
        $order = GroupListOrder::where('id',$oid)->first();
        //商品信息
        $good = GroupList::where('id',$order['gid'])->first();
        if(!$order){
            return ['code'=>0,'nsg'=>"该订单信息有误"];
        }
      
        //订单详情
        $add['linkman'] = $order['linkman'];
        $add['linktel'] = $order['linktel'];
        $add['address'] = $order['address'];

        $status = 0;
        $send_time = '无';
        $over_time = '无';

        //购买记录
        $state = 1;//拼团(4拼团失败 3中奖  2未中奖  1待成团)
        if(GroupListLog::where('oid',$order['id'])->where('state',4)->first()){
            $state = 4;
        }
        if(GroupListLog::where('oid',$order['id'])->where('state',2)->first()){
            $state = 2;
        }
        if(GroupListLog::where('oid',$order['id'])->where('state',1)->first()){
            $state = 1;
        }
        if(GroupListLog::where('oid',$order['id'])->where('state',3)->first()){
            $listlog = GroupListLog::where('oid',$order['id'])->where('state',3)->first();
            $status = $listlog['status'];
            $state = 3;
            $over_time = $listlog['over_time'];
            $send_time = $listlog['send_time'];

        }
        $state_cy['state'] = $state;
        $state_cy['end'] = strtotime($good['end']);
        $state_cy['wish_num'] = '未中奖';
        $state_cy['win_user_pic'] = 'http://'.$_SERVER['HTTP_HOST'].'/user.png';
        $state_cy['win_user_tel'] = '130****0897';
        $state_cy['win_oid'] = GroupListLog::where('oid',$order['id'])->where('state',3)->value('id');

        //中奖号
        $wish_group_order = GroupListLog::where('oid',$order['id'])->where('state',3)->value('num');
        if($wish_group_order){
            $state_cy['wish_num'] = $wish_group_order.'号';
        }
        $win_group_order_res = GroupListLog::where('gid',$order['gid'])->where('curcle',$order['curcle'])->where('state',3)->first();
        
        if($win_group_order_res){
            $user = UserModel::where('id',$win_group_order_res['uid'])->first();
            $user_party = UserLoginModel::where('uid',$win_group_order_res['uid'])->orderBy('picname','desc')->first();
            if($user['picname']){
                $state_cy['win_user_pic'] = 'http://'.$_SERVER['HTTP_HOST'].$user['picname'];
            }else{
                if($user_party['picname']){
                    $state_cy['win_user_pic'] = $user_party['picname'];
                }
            }

            if($user['email']){
                $state_cy['win_user_tel'] = substr_replace($user['email'], '****', 3, 4);
            }
            //中奖手机号
            if($user['phone']){
                $state_cy['win_user_tel'] = substr_replace($user['phone'], '****', 3, 4);
            }
        }
       
        //商品信息
        $group = GroupListCite::where('gid',$order['gid'])->where('curcle',$order['curcle'])->first();
        if(!$group){
            $group = GroupList::where('id',$order['gid'])->first();
            $orders['picname'] = $group['picname'];
            $orders['name'] = $group['name'];
        }else{
            $orders['picname'] = $group['gpic'];
            $orders['name'] = $group['gname'];
        }
     
        
        $orders['sell'] = $order['sell'];
        $orders['sum'] = $order['sum'];
        $orders['num'] = $order['num'];
        $orders['sn'] = $order['sn'];
        $orders['total'] = $order['sum'];
        $orders['paytype'] = $order['paytypename'];
        $orders['time'] = date('Y-m-d H:i:s',$order->created_at->timestamp);
        $orders['profit'] = ceil($group['charge']/$group['nums'])*GroupListLog::where('oid',$order['id'])->count();
        $orders['shares'] = $group['shares'];
        $orders['send_time'] = $send_time;
        $orders['over_time'] = $over_time;
        $orders['status'] = $status;
    
        //选择的位置
        $chose_site = GroupListLog::where('oid',$order['id'])->orderBy('num','asc')->get();
        $site = [];
        foreach($chose_site as $k=>$v){
            $site[] = $v['num'].'号';
        }

        

        $data['add'] = $add;
        $data['state'] = $state_cy;
        $data['order'] = $orders;
        $data['site'] = $site;
        return ['code'=>1,'msg'=>"返回数据",'data'=>$data];
    }

    //开关
    public function switch(){
        $val = ConfigModel::getValue('switch_state');
        if($val == 2){
            return ['code'=>0,'msg'=>'拼团尚未开启'];
        }
        return ['code'=>1,'msg'=>"ok"];
    }

    //测试 过期商品
    public function indate(){
        DB::beginTransaction();
		try{
			//拼团商品到期之后，将商品的状态更改为已过期，开关关闭，第几轮+1 ，计算到期的订单
            $list = GroupList::where('end','<=',date('Y-m-d H:i:s'))->where('switch',1)->get();
			foreach($list as $k=>$v){
                $no_order = GroupListOrder::where('gid',$v['id'])->where('curcle',$v['curcle'])->get();
                
				foreach($no_order as $key=>$val){
					//商品过期，未拼团成功的商品   本金返还
					//用户信息
					$user = UserModel::where('id',$val['uid'])->first();
					if($val['paytype'] == 1 || $val['paytype'] == 2){
						UserWalletModel::handleAccount($user['id'],$val['sum'],'+','拼团失败，返还本金',$val['paytype'],18);
					}
					//更改拼团记录的状态为4
					GroupListLog::where('oid',$val['id'])->update(['state'=>4]);
					//更改拼团订单的状态为完成
					GroupListOrder::where('id',$val['id'])->update(['state'=>1]);
					//更改商品的状态
					GroupList::where('id',$val['gid'])->update(['switch'=>2]);
					GroupList::where('id',$val['gid'])->increment('curcle');
				}
			}

			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
        }
        return ['code'=>1,'msg'=>"操作完成"];
    }

    //收货
    public function send_ok(){
        $id = request()->id;
        $paypass = request()->paypass;
        if(!$paypass){
            return ['code'=>0,'msg'=>'请输入二级密码'];
        }
        $user = UserModel::where('id',request()->uid)->first();
        //支付密码
        if (!Hash::check($paypass, $user['paypass'])) {
            return ['code' => 0, 'msg' => '支付密码输入有误'];
        }
        $list = GroupListLog::where('state',3)->where('id',$id)->where('status',2)->first();
        if(!$list){
            return ['code'=>0,'msg'=>'该订单有误!'];
        }
        DB::beginTransaction();
        try{
            GroupListLog::where('id',$id)->update(['status'=>3,'over_time'=>date('Y-m-d H:i:s')]);
            DB::commit();
        }catch(Exception $e){
            DB::rollBack();
            return ['code'=>0,'msg'=>"收货失败"];
        }
        return ['code'=>1,'msg'=>'收货成功'];

    }
}